import React, { Suspense } from 'react';
import { Layout, message } from 'antd';
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
import Media from 'react-media';
import router from 'umi/router';
import $ from 'jquery';
import logo from '../assets/logo.svg';
import Footer from './Footer';
import Header from './Header';
import Context from './MenuContext';
import SiderMenu from '@/components/SiderMenu';
import getPageTitle from '@/utils/getPageTitle';
import styles from './BasicLayout.less';
import TabPages from '@/components/TabPages';
import Exception403 from '@/pages/Exception/403';
import Exception404 from '@/pages/Exception/404';

// lazy load SettingDrawer
const SettingDrawer = React.lazy(() => import('@/components/SettingDrawer'));

const { Content } = Layout;

const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
  },
};

/*
const BrowserLogger = require('alife-logger');
// BrowserLogger.singleton(conf) conf传入config配置
const __bl = BrowserLogger.singleton({
  pid:"gtb1slox38@8582141da5fdd86",appType:"web",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?"
  /!*pid: 'your-project-id',
  imgUrl: 'https://arms-retcode.aliyuncs.com/r.png?', // 设定日志上传地址,新加坡部署可选`https://arms-retcode-sg.aliyuncs.com/r.png?`*!/
  // 其他config配置
});
*/


class BasicLayout extends React.Component {

  componentWillMount() {
    window.theRequest = {};
    window.theRequestt = this.props.location.search;
    if (this.props.location.search.indexOf('?') !== -1) {
      const str = this.props.location.search.substr(1);
      const strs = str.split('&');
      for (let i = 0; i < strs.length; i++) {
        window.theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
      }
    }
  }

  componentDidMount() {
    if (
      localStorage.getItem('versionX') !== `${window.versionX}` &&
      window.theRequest.header !== '1'
    ) {
      router.push(`/user/login?ran=${window.versionX}`);
      /* setTimeout(() => {
        // window.location.reload(true);
        $.ajax({
          url:'http://fss.91stock.net/#/user/login',
          dataType:'json',
          data:{},
          cache:false,
          ifModified :true ,
          success:function(response){
            //操作
          },
          async:false
        });
        message.success('更新至版本:'+window.versionX);
      }, 1000); */
    }

    const {
      dispatch,
      route: { routes, path, authority },
    } = this.props;
    let  that = this;
    if(window.theRequest.header !== '1' ){
      dispatch({
        type: 'menu/authRoutes',
      });
      dispatch({
        type: 'user/fetchCurrent',
      });
      dispatch({
        type: 'setting/getSetting',
      });
      dispatch({
        type: 'menu/getMenuData',
        payload: { routes, path, authority },
      });
      dispatch({
        type: 'menu/getCollection',
      });
    }
    }

  getContext() {
    const { location, breadcrumbNameMap } = this.props;
    return {
      location,
      breadcrumbNameMap,
    };
  }

  getLayoutStyle = () => {
    const { fixSiderbar, isMobile, collapsed, layout } = this.props;
    if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
      if (window.theRequest.header === '1') {
        return {
          paddingLeft: '0px',
        };
      }
      return {
        paddingLeft: collapsed ? '80px' : '256px',
      };
    }
    return null;
  };

  handleMenuCollapse = collapsed => {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  };

  renderSettingDrawer = () => {
    // Do not render SettingDrawer in production
    // unless it is deployed in preview.pro.ant.design as demo
    if (process.env.NODE_ENV === 'production' && APP_TYPE !== 'site') {
      return null;
    }
    return <SettingDrawer />;
  };

  render() {
    const {
      navTheme,
      layout: PropsLayout,
      children,
      location: { pathname },
      isMobile,
      menuData,
      breadcrumbNameMap,
      fixedHeader,
      collection
    } = this.props;
    let collectionFlag = false;
    for (let i = 0; i < collection.length; i++) {
      const item =  collection[i];
      if(item.url === this.props.location.pathname){
        collectionFlag = true;
      }
    }
    const isTop = PropsLayout === 'topmenu';
    const contentStyle = !fixedHeader ? { paddingTop: 0 } : {};

    const layout = (
      <Layout>
        {(isTop && !isMobile) || window.theRequest.header === '1' ? null : (
          <SiderMenu
            logo={logo}
            theme={navTheme}
            onCollapse={this.handleMenuCollapse}
            menuData={menuData}
            isMobile={isMobile}
            {...this.props}
          />
        )}
        <Layout
          style={{
            ...this.getLayoutStyle(),
            minHeight: '90vh',
          }}
        >
          {window.theRequest.header === '1' ? null : (
            <Header
              menuData={menuData}
              handleMenuCollapse={this.handleMenuCollapse}
              logo={logo}
              isMobile={isMobile}
              {...this.props}
            />
          )}
          <Content
            className={window.theRequest.header === '1' ? styles.contentNoHeader : styles.content}
            style={contentStyle}
          >
            {window.theRequest.header === '1' ? (
              children
            ) : (
              <TabPages
                {...this.props}
                addCollection={ this.addCollection.bind(this)}
                deleteCollection={ this.deleteCollection.bind(this)}
                collectionFlag = {collectionFlag}
                homePageKey="/Pandect"
                errorPage={<Exception403 />}
              />
            )}
          </Content>
          <Footer />
        </Layout>
      </Layout>
    );
    return (
      <React.Fragment>
        <DocumentTitle title={getPageTitle(pathname, breadcrumbNameMap)}>
          <ContainerQuery query={query}>
            {params => (
              <Context.Provider value={this.getContext()}>
                <div className={classNames(params)}>{layout}</div>
              </Context.Provider>
            )}
          </ContainerQuery>
        </DocumentTitle>
        <Suspense fallback={null}>{this.renderSettingDrawer()}</Suspense>
      </React.Fragment>
    );
  }

  addCollection(activeKey){
    const {
      dispatch,
    } = this.props;
    let  that = this;

    dispatch({
      type: 'menu/addCollection',
      payload: { url:activeKey,  permissionname:window.userName  },
      callback:(res)=>{
        dispatch({
          type: 'menu/getCollection',
        });
      }
    });
  }
  deleteCollection(activeKey){
    const {
      dispatch,
    } = this.props;
    let  that = this;

    dispatch({
      type: 'menu/deleteCollection',
      payload: { url:activeKey, permissionname:window.userName  },
      callback:(res)=>{
        dispatch({
          type: 'menu/getCollection',
        });
      }
    });
  }
}

export default connect(({ global, setting, menu: menuModel }) => ({
  collapsed: global.collapsed,
  layout: setting.layout,
  menuData: menuModel.menuData,
  breadcrumbNameMap: menuModel.breadcrumbNameMap,
 collection: menuModel.collection,
  ...setting,
}))(props => (
  <Media query="(max-width: 599px)">
    {isMobile => <BasicLayout {...props} isMobile={isMobile} />}
  </Media>
));
